import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/dashboard',
      meta: { title: '首页' }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/auth/LoginView.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: () => import('../views/DashboardView.vue'),
      meta: { title: '仪表盘' }
    },
    {
      path: '/admin',
      name: 'admin',
      component: () => import('../views/admin/AdminView.vue'),
      meta: { title: '管理员管理' }
    },
    {
      path: '/role',
      name: 'role',
      component: () => import('../views/role/RoleView.vue'),
      meta: { title: '角色管理' }
    },
    {
      path: '/permission',
      name: 'permission',
      component: () => import('../views/permission/PermissionView.vue'),
      meta: { title: '权限管理' }
    },
    {
      path: '/article',
      name: 'article',
      component: () => import('../views/article/ArticleView.vue'),
      meta: { title: '文章管理' }
    },
    {
      path: '/category',
      name: 'category',
      component: () => import('../views/article/CategoryView.vue'),
      meta: { title: '分类管理' }
    },
    {
      path: '/settings',
      name: 'settings',
      component: () => import('../views/settings/SettingsView.vue'),
      meta: { title: '网站设置' }
    },
    {
      path: '/links',
      name: 'links',
      component: () => import('../views/links/LinksView.vue'),
      meta: { title: '友情链接' }
    },
    {
      path: '/menu',
      name: 'menu',
      component: () => import('../views/menu/MenuView.vue'),
      meta: { title: '菜单管理' }
    },
    {
        path: '/member',
        name: 'member',
        component: () => import('../views/member/MemberView.vue'),
        meta: { title: '会员管理' }
      },
      {
        path: '/member-level',
        name: 'member-level',
        component: () => import('../views/member-level/MemberLevelView.vue'),
        meta: { title: '会员等级' }
      },
      {
        path: '/log',
        name: 'log',
        component: () => import('../views/log/LogView.vue'),
        meta: { title: '操作日志' }
      }
    ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = `${to.meta.title} - 后台管理系统`
  
  // 检查是否需要登录
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  const requiresAuth = to.path !== '/login'
  
  if (requiresAuth && !isLoggedIn) {
    // 需要登录但未登录，重定向到登录页
    next('/login')
  } else if (to.path === '/login' && isLoggedIn) {
    // 已登录但访问登录页，重定向到仪表盘
    next('/dashboard')
  } else {
    // 其他情况正常导航
    next()
  }
})

export default router
